import React, { useState, useMemo } from 'react';
import s from '../style.module.css';
import Breadcrumb, { Item } from '../../../../../components/Breadcrumb';
import Helper from '../../../../../components/Helper';
import { withRouter } from 'react-router';
import cn from 'classnames'
import SecurityRating from '../SecurityRating';
import { IconS, Download } from '../SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../../../components/Label';
import Select from '@knownsec/react-component/dist/Select';
import fetchFer from 'API/fetch';
import Message from '@knownsec/react-component/dist/Message'
import Loading from '@knownsec/react-component/dist/Loading'
import Button from '@knownsec/react-component/dist/Button'
import { turnToUrlparam, GetQueryString } from '../../../../../helpers/getUrlParams';
import { datetime } from '../../../../../../common/formatter';
import moment from 'moment'

import WebTaskDetail from '../WebTaskDetail';
import { cloneDeep } from 'lodash';
const infoObj = {
	target_url: '资产地址',
	target_ip: '响应IP',
	url_count: '已扫描URL数',
	waf_info: '防御信息',
	result: '监测结果'
};
const taskMap = {
	vul: 'Web漏洞',
	ssl: 'SSL安全威胁',
	security_event: '安全事件',
	content: '内容违规'
}
const taskSubMap = {
	vul: {
		high: '高危',
		medium: '中危',
		low: '低危'
	}
}
function History({
	match: {
		params: { assetType, jid },
	},
	location,
}) {
	const atid = GetQueryString(location.search, 'id');
	const type = GetQueryString(location.search, 'type');
	const last = GetQueryString(location.search, 'last');
	const task_types = GetQueryString(location.search, 'task_types');
	const asset_task_id = GetQueryString(location.search, 'asset_task_id');
	const task_id = GetQueryString(location.search, 'task_id');
	const [selVal, setSelVal] = useState([]);
	const [timeOpt, setTimeOpt] = useState([]);
	const [manualT, setManualT] = useState();
	const [detail, setDetail] = useState([{}]);
	const [loading, setLoading] = useState(false)
	const [overview, setOverview] = useState(null)
	const getHistoryDetail = async () => {
		setLoading(true)
		const sendData = {
			task_types,
			asset_task_id,
			task_id: selVal[0]
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(
			`/api/v2/tasks/web_security/type/detail?${params}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			const data = cloneDeep(res.data)
			data.settings = data.task_settings
			const scoreInfo = res.data?.score_info
			let total = scoreInfo?.count || 0
			if (taskSubMap[task_types]) {
				total = 0
				Object.keys(taskSubMap[task_types]).reduce((t, key) => {
					if (scoreInfo[key]) {
						total += scoreInfo[key]
					}
				})
			}
			const overV = data?.overview
			overV.score = scoreInfo.score
			overV.url_count = overV.url_count + ''
			overV.result = '发现'
			if (total) {
				overV.result += total + '个' + taskMap[task_types]
				if (taskSubMap[task_types]) {
					overV.result += '，其中'
					overV.result += Object.keys(taskSubMap[task_types]).reduce((t, key) => {
						if (scoreInfo[key]) {
							t.push(taskSubMap[task_types][key] + scoreInfo[key] + '个')
						}
						return t
					}, []).join('，')
				}
				overV.result += '，为了您的资产安全，请及时修复并加固安全防护。'
			} else {
				overV.result = '未发现任何风险，您的Web资产处于安全状态。'
			}
			setOverview(overV)
			setDetail(data);
			setLoading(false)
		} else {
			Message.show({ type: res.status, message: res.message })
		}
	};
	const resDemo = e => {
		const aa = e && e.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	// 获取时间列表
	useMemo(async () => {
		const sendData = {
			task_types: task_types === 'security_event' ? 'securityEvent' : task_types,
			asset_task_id
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(`/api/v2/repodatas/task_completed_times?${params}`, {
			method: 'GET',
		}).catch(error => {
			return error;
		});
		const time = res.data.map(e => {
			if (e.id === task_id) {
				setManualT(datetime(e.time));
				setSelVal([e.id]);
			}
			return { label: moment(e.time).format('YYYY-MM-DD HH:mm:ss'), value: e.id };
		});
		setTimeOpt(time);
		!last && setSelVal([time[0].value]);
	}, [assetType]);

	const [downloadTimer, setDownloadTimer] = React.useState(false);
	const downloadReport = () => {
		if (downloadTimer) return false;
		setDownloadTimer(true);
		const text = `[${overview.job_name}]ScanV安全监测报告.docx`;
		fetch(`/api/v2/report/one_task/download?task_id=${selVal[0]}`, {
			method: 'GET',
		}).then(res => {
			if (res.ok) {
				return res.blob();
			}
		})
		.then(blob => {
			const url = (window.webkitURL || window.URL).createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = text;
			a.click();
			setDownloadTimer(false);
		})
		.catch(() => {
			Message.show({
				type: 'error',
				message: `导出${text}`,
				placement: 'top',
				style: { width: '25rem' },
			});
			setDownloadTimer(false);
		});
	}

	React.useEffect(() => {
		if (selVal.length > 0) getHistoryDetail();
	}, [selVal]);
	return (
		<div className={s.taskMain}>
			<div className='df aic jcsb'>
				<Breadcrumb>
					<Item key="job-manage" disabled>
						任务管理
					</Item>
					<Item key="web-task">Web安全监测</Item>
					<Item key={`detail?id=${asset_task_id}&type=schedule&tag=${task_types}`}>监测详情</Item>
					<Item key="">{taskMap[task_types]}历史任务</Item>
				</Breadcrumb>
				<div className={cn(s.df, s.aic)}>
					<div className={cn(s.df, s.aic, s.fs20)}>
						历史监测结果:
						<Select
							pro
							value={selVal}
							getPopupContainer={triggerNode => triggerNode}
							placeholder="检测历史"
							option={timeOpt}
							className={cn(s.sel, s.m0_10_0_5, s.w210)}
							clearable
							onChange={({ selectedItem }) => {
								setSelVal([selectedItem[0].value]);
							}}
						/>
					</div>
					{detail?.job_id && <Button pro className={s.downloadPlain} onClick={downloadReport}>
						<svg width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
								<g id="控件" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
										<g id="Web安全任务详情表头" transform="translate(-1052.000000, -33.000000)" fill-rule="nonzero">
												<g id="编组-3" transform="translate(1032.000000, 25.000000)">
														<g id="下载" transform="translate(20.000000, 8.000000)">
																<rect id="矩形" fill="#000000" opacity="0" x="0" y="0" width="20" height="20"></rect>
																<path d="M16.3636364,17.9545454 L3.63636363,17.9545454 C2.75772881,17.9545454 2.04545455,17.2422712 2.04545455,16.3636364 L2.04545455,14.5454546 C2.04545455,14.1688968 2.35071495,13.8636364 2.72727273,13.8636364 C3.10383052,13.8636364 3.40909092,14.1688968 3.40909092,14.5454546 L3.40909092,16.3636364 C3.40909093,16.4891556 3.51084438,16.5909091 3.63636363,16.5909091 L16.3636364,16.5909091 C16.4891556,16.5909091 16.5909091,16.4891556 16.5909091,16.3636364 L16.5909091,14.5454546 C16.5909091,14.1688968 16.8961695,13.8636364 17.2727273,13.8636364 C17.6492851,13.8636364 17.9545454,14.1688968 17.9545454,14.5454546 L17.9545454,16.3636364 C17.9545454,17.2422712 17.2422712,17.9545454 16.3636364,17.9545454 L16.3636364,17.9545454 Z M10,12.5090909 C9.81758439,12.5090909 9.64276921,12.4360263 9.51463893,12.3061877 C9.38650865,12.176349 9.31574961,12.0005812 9.31818182,11.8181818 L9.31818182,2.72727273 C9.31818182,2.35071495 9.62344222,2.04545455 10,2.04545455 C10.3765578,2.04545455 10.6818182,2.35071495 10.6818182,2.72727273 L10.6818182,11.8181818 C10.6842504,12.0005812 10.6134913,12.176349 10.4853611,12.3061877 C10.3572308,12.4360263 10.1824156,12.5090909 10,12.5090909 L10,12.5090909 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 L4.97272727,8.93181818 C4.84392179,8.80457551 4.77142679,8.63105676 4.77142679,8.45 C4.77142679,8.26894324 4.84392179,8.09542449 4.97272727,7.96818182 C5.23994534,7.70479205 5.66914556,7.70479205 5.93636363,7.96818182 L10.4818182,12.5136364 C10.6106237,12.640879 10.6831187,12.8143978 10.6831187,12.9954546 C10.6831187,13.1765113 10.6106237,13.3500301 10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 Z M10,13.6772727 C9.81933074,13.6766185 9.64620538,13.6047552 9.51818182,13.4772727 C9.38937634,13.3500301 9.31688134,13.1765113 9.31688134,12.9954546 C9.31688134,12.8143978 9.38937634,12.640879 9.51818182,12.5136364 L14.0636364,7.96818182 C14.3308544,7.70479205 14.7600547,7.70479205 15.0272727,7.96818182 C15.1560782,8.09542449 15.2285732,8.26894324 15.2285732,8.45 C15.2285732,8.63105676 15.1560782,8.80457551 15.0272727,8.93181818 L10.4818182,13.4772727 C10.3537946,13.6047552 10.1806693,13.6766185 10,13.6772727 L10,13.6772727 Z" id="形状" fill="#0B6FD6"></path>
														</g>
												</g>
										</g>
								</g>
						</svg>
						下载报告
					</Button>}
				</div>
			</div>
			<div className={cn(s.content, s.pt0)}>
				<div className={s.header}>
					<div className={s.left}>
						<SecurityRating score={100 - overview?.score} />
					</div>
					<div className={s.right}>
						{/* <div>
						<Download />
						<a>下载报告</a>
					</div> */}
					<div className={cn(s.mb16)}>
						<div className={s.title} title={overview?.name}>
							任务名称：{overview?.name}
						</div>
					</div>
						<div className={s.info}>
							<div className={cn(s.df, s.aic, s.mb16)}>
								{Object.keys(infoObj).slice(0, 2).map((e, i) => {
									return (
										<p className={cn(s.flex1)} key={e}>
											<span className={s.infoName}>{infoObj[e]}</span>：
											<span className={s.infoVal}>{(overview && overview[e]) || '- -'}</span>
										</p>
									);
								})}
							</div>
							<div className={cn(s.df, s.aic)}>
								{Object.keys(infoObj).slice(2, 4).map(e => {
									return (
										<p className={cn(s.mb16, s.flex1)} key={e}>
											<span className={s.infoName}>{infoObj[e]}</span>：
											<span className={s.infoVal}>{(overview && overview[e]) || '- -'}</span>
										</p>
									);
								})}
							</div>
							{Object.keys(infoObj).slice(4).map(e => {
								return (
									<div className={s.rBox}>
										<p className={cn(s.df, s.aic)}>
											<IconS />
											<span className={s.ml12}>{infoObj[e]}</span>
											<Helper
												className={s.cp}
												overlay="同步资产最新一次Web安全监测结果。"
												placement="top"
											/>
										</p>
										<p
											dangerouslySetInnerHTML={{ __html: resDemo((overview && overview[e]) || '') }}
											className={s.infoVal}
										></p>
									</div>
								);
							})}
						</div>
					</div>
				</div>
				<div className={s.infoBody}>
					<Label className={s.labelDetail}>监测详情</Label>
					<div className={s.pr}>
						<Loading show={loading} />
						<WebTaskDetail taskType={'schedule'} task_types={task_types} data={{ task_id, [task_types]: detail }} tid={selVal} atid={asset_task_id} isHistory={true} />
					</div>
				</div>
			</div>
		</div>
	);
}
History.propTypes = {
	location: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(History);
